var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var path = require('path');

//在线用户
var onlineUsers = {};
//在线人数
var onlineCount = 0;

app.use(express.static(path.join(__dirname, 'www')));

app.get('/', function(req, res){
  res.sendfile('login.html');
});

app.get('/index', function(req, res){
  res.sendfile('index.html');
});

io.on('connection', function(socket){
  console.log('a user connected');
  var socketID = socket.id;
  onlineUsers[socketID] = {
    socket:socket
  };

  //广播用户加入消息
  socket.on('join',function(data){
    console.log(data.username);
    onlineUsers[socketID].username = data.username;
    onlineUsers[socketID].userimg = data.userimg;
    console.log(onlineUsers[socketID].username);
    //在线人数+1
    onlineCount++;
    socket.emit('broadcast_join',{
      onlineCount:onlineCount,
      username:data.username
    });
  });

  socket.on('disconnect', function(){
    console.log('user disconnected');
  });
  socket.on('chat message', function(msg){
    console.log(onlineUsers[socketID].username + ' say:' + msg);
    socket.broadcast.emit('chatMsg',{
      username:onlineUsers[socketID].username,
      userimg:onlineUsers[socketID].userimg,
      content:msg
    });
  });

});

http.listen(3000, function(){
  console.log('listening on *:3000');
});